import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_module/binding/custom_binding.dart';
import 'package:flutter_module/bloc/custom_bloc_observer.dart';
import 'package:flutter_module/router/app_global_page_visibilityo_bserver.dart';
import 'package:flutter_module/router/routers.dart';
import 'package:flutter_module/util/language_res/string_res.dart';
import 'package:flutter_module/util/log_u.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

void main() {
  PageVisibilityBinding.instance
      .addGlobalObserver(AppGlobalPageVisibilityObserver());

  ///flutter_boost:这里的CustomFlutterBinding调用务必不可缺少，用于控制Boost状态的resume和pause
  CustomFlutterBinding();

  Bloc.observer = const CustomBlocObserver();

  //https://docs.flutter.cn/testing/errors
  //异常捕获---start---
  //处理所有类型的错误
  var onError = FlutterError.onError;
  FlutterError.onError = (FlutterErrorDetails details) {
    onError?.call(details); //调用默认的onError处理
    reportError(details);
  };
  PlatformDispatcher.instance.onError = (error, stack) {
    reportError(error);
    return true;
  };
  //异常捕获---end---

  runApp(const MyApp());
}

//待完善
void reportError(Object errorObject) {
  // if(errorObject is FlutterErrorDetails){
  //   LogU.log("reportError $errorObject");
  // }
  LogU.log("reportError $errorObject");
}

///flutter_boost:创建一个自定义的Binding，继承和with的关系如下，里面什么都不用写
class CustomFlutterBinding extends WidgetsFlutterBinding
    with BoostFlutterBinding {}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // final easyLoad = EasyLoading.init();

  /// flutter_boost:设置路由工厂
  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    FlutterBoostRouteFactory? func = RouteGet.routerMap[settings
        .name!]; //settings.name!必须有!，否则FlutterBoostApp的第一个参数会报错。具体代码参考官方demo；
    if (func == null) {
      return null;
    }
    return func(settings, uniqueId);
  }

  Widget appBuilder(Widget home) {
    /// GetX改造步骤：1、修改MaterialApp成GetMaterialApp
    ///
    /// 在 MaterialApp 组件外层包裹一层 ScreenUtilInit 组件，方式一适配可行，方式二适配存在问题（暂时不确定是否使用使用不当导致的）
    /// https://github.com/OpenFlutter/flutter_screenutil/blob/master/README_CN.md
    return ScreenUtilInit(
      /// 设置设计稿宽高
      designSize: Size(360, 690),

      /// 设置原本要显示的 MaterialApp
      builder: (context, child) {
        return GetMaterialApp(
            //[getX多语言](https://juejin.cn/post/7039637076962181157)
            //使用 Get.updateLocale 更改语言：Get.updateLocale(const Locale('en', 'US'));
            translations: StringRes(),
            //translations 传入的就是我们定义好的继承自 Translations 的类的对象
            locale: const Locale('zh', 'CN'),
            //locale 我们默认使用的语言
            // locale: window.locale,//locale 也可以使用获取系统语言环境：
            fallbackLocale: const Locale('en', 'US'),
            //fallbackLocale  当我们默认语言资源没有时就会使用 fallbackLocale 配置的资源
            initialBinding: CustomBinding(),
            debugShowCheckedModeBanner: true,
            home: home,
            builder: EasyLoading.init());
      },
      child: home,
    );
    // return GetMaterialApp(
    //     initialBinding: CustomBinding(),
    //     home: home,
    //     debugShowCheckedModeBanner: true,
    //
    //     ///flutter_boost:必须加上builder参数，否则showDialog等会出问题
    //     // builder: (_, __) {
    //     //   return home;
    //     // },//尝试注释，待观察
    //     builder: EasyLoading.init() //初始化单个，下方是初始化多个(待测试效果)
    //     // builder: (context, child) {
    //     //   SharedPreferencesU.preInit();
    //     //   child = easyLoad(context, child);
    //     //   return child;
    //     // }
    //     );
  }

  // @override
  // void initState() {
  //   super.initState();
  //     WidgetsBinding.instance.addPostFrameCallback((_) async {
  //       SystemChrome.setSystemUIOverlayStyle(
  //         SystemUiOverlayStyle(
  //           systemNavigationBarColor: AppColors.color_6c1bc,
  //           systemNavigationBarDividerColor: AppColors.color_3cceaf,
  //           statusBarColor: Colors.transparent,
  //           systemNavigationBarIconBrightness: Brightness.dark,
  //         ),
  //       );
  //     });
  // }

  @override
  Widget build(BuildContext context) {
    // return AnnotatedRegion(
    //   value: SystemUiOverlayStyle.dark.copyWith(
    //     statusBarColor: Colors.transparent,
    //     systemNavigationBarColor: AppColors.color_6c1bc,
    //     systemNavigationBarDividerColor: AppColors.color_3cceaf,
    //     systemNavigationBarIconBrightness: Brightness.dark,
    //   ),
    // child:  FlutterBoostApp(
    //
    //   /// flutter_boost:设置路由
    //   routeFactory,
    //
    //   /// flutter_boost:如果自定了appBuilder，需要将传入的参数添加到widget层次结构中去，否则会导致FluttBoost初始化失败。
    //   appBuilder: appBuilder,
    // ),);
    ///flutter_boost:设置FlutterBoostApp路由配置
    return FlutterBoostApp(
      /// flutter_boost:设置路由
      routeFactory,

      /// flutter_boost:如果自定了appBuilder，需要将传入的参数添加到widget层次结构中去，否则会导致FluttBoost初始化失败。
      appBuilder: appBuilder,
    );
  }
}
